package com.xbai.tx;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author jxbai
 * @desc 声明式事务
 * 环境搭建
 * 1、导入相关依赖：数据源、数据库驱动、Spring-JDBC 模块
 * 2、配置数据源、JdbcTemplate（Spring 提供的简化数据库的工具）操作数据
 * 3、给方法上标注 @Transactional 表示当前方法是一个事务方法
 * 4、@EnableTransactionManagement 开启基于注解的事务管理功能
 * @date 2021/5/13 0013
 */
@Configuration
@ComponentScan("com.xbai.tx")
@EnableTransactionManagement
public class TxConfig {

    @Bean
    public PlatformTransactionManager platformTransactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 数据源
     * @return
     * @throws PropertyVetoException
     */
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://1.116.186.202:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
        //Spring 对 Configuration 类会特殊处理，给容器中加组件的方法，多次调用都只是从容器中找组件而已
        return new JdbcTemplate(dataSource());
    }
}

